package models

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
)

// 连接数据库
func OpenDB() *gorm.DB {
	// 连接数据库的url
	sql_url := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=%t&loc=%s",
		viper.GetString("db.username"),
		viper.GetString("db.password"),
		viper.GetString("db.addr"),
		viper.GetString("db.name"),
		true,
		"Local",
	)
	db, err := gorm.Open("mysql", sql_url)
	fmt.Println(sql_url)
	if err != nil {
		fmt.Println("Database connection filed.", err)
	} else {
		fmt.Println("Database connection success!")
	}
	return db
}

type Database struct {
	Self *gorm.DB
}

var DB *Database

func Init() {
	DB = &Database{
		Self: OpenDB(), // 创建数据库连接
	}
	// automigrate 自动将程序定义好的数据模型迁移到数据库
	DB.Self.AutoMigrate(&UserInfo{}, &Recipes{}, &Comments{}, &CookingTools{}, &Favorites{}, &Follows{}, &HealthGuides{}, &Ratings{}, &RegionalFoods{}, &Suggestions{}, &Tags{})
}

// 关闭数据库连接

func Close() {
	DB.Self.Close()
}
